package org.system.core.service.system;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.system.core.common.Constants;
import org.system.core.domain.entity.SysUser;
import org.system.core.domain.model.RegisterBody;
import org.system.core.exception.UserVerifyException;
import org.system.core.utils.MessageUtils;
import org.system.core.utils.SecurityUtils;
import org.system.core.utils.StringUtils;

/**
 * @author baoRoot
 */
@Service
public class SysRegisterService {

    private static final Logger logger = LoggerFactory.getLogger(SysRegisterService.class);

    @Autowired
    private SysUserService userService;

    public void register(RegisterBody registerBody){
        String username = registerBody.getUsername();
        String password = registerBody.getPassword();
        SysUser user = new SysUser();
        user.setUserName(username);
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
            logger.info("用户名或密码不能为空");
            throw new UserVerifyException(MessageUtils.message("system.user.password_and_username"));
        }
        if (username.length() < Constants.USERNAME_MIN_LENGTH || username.length() > Constants.USERNAME_MAX_LENGTH) {
            logger.info("用户名称格式错误");
            throw new UserVerifyException(MessageUtils.message("system.user.username_format_error"));
        }
        if (password.length() < Constants.PASSWORD_MIN_LENGTH || password.length() > Constants.PASSWORD_MAX_LENGTH) {
            logger.info("用户密码格式错误");
            throw new UserVerifyException(MessageUtils.message("system.user.password_format_error"));
        }
        if (userService.checkUserNameUnique(user)) {
            logger.info("注册的用户： {} 已存在", username);
            throw new UserVerifyException(MessageUtils.message("system.user.exist_username"));
        }
        user.setNickName(username);
        user.setPassword(SecurityUtils.encryptPassword(password));
        boolean registerFlag = userService.registerUser(user);
        if (!registerFlag) {
            logger.info("注册用户失败，请联系系统管理员");
            throw new UserVerifyException(MessageUtils.message("system.user.register_error"));
        }
    }
}
